package com.wryyyyy.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class ExcelListener extends AnalysisEventListener<Map<Integer, Object>> {
    //创建list集合封装最终的数据
    List<String> tableHead = new ArrayList<>();
    List<Map<Integer, Object>> list = new ArrayList<>();

    // 行
    Integer row = 0;

    // 列
    Integer col = 0;

    public List<Map<Integer, Object>> getDataList() {
        return list;
    }

    public List<String> getTableHead() {
        return tableHead;
    }

    public Integer getRow() {
        return row;
    }

    public Integer getCol() {
        return col;
    }

    //一行一行去读取excle内容，把每行的内容封装到实体类对象中
    //注：读取是从第二行开始读取，第一行默认为表头，不进行读取。
    @Override
    public void invoke(Map<Integer, Object> xN, AnalysisContext analysisContext) {
        col = 0;
        for (Integer i : xN.keySet()) {
            if (i != 0) {
                BigDecimal value = new BigDecimal(xN.get(i).toString());
                String formattedValue = value.setScale(2, RoundingMode.HALF_UP).toString();
                xN.put(i, formattedValue);
            } else {
                row++;
            }
            col++;
        }

        log.debug("***" + xN);
        list.add(xN);
    }

    //读取excel表头信息，headMap即为表头信息
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        log.debug("表头信息：" + headMap);
        for (Integer i : headMap.keySet()) {
            String s = headMap.get(i);
            if (s != null) {
                tableHead.add(headMap.get(i));
            }
        }
    }

    //读取完成后执行
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }
}